/**
 * 登录状态管理
 */
import axios from 'axios'
import setting from '@/config/setting'
import { formatMenus } from 'ele-admin-pro'

export default {
  namespaced: true,
  state: {
    // 当前用户信息
    user: setting.takeUser(),
    // 当前用户权限
    authorities: [],
    // 当前用户角色
    roles: [],
    // 当前用户的菜单
    menus: null,
    // 当前登录用户所拥有的权限节点
    permission: []
  },
  mutations: {
    // 修改值
    SET(state, obj) {
      state[obj.key] = obj.value
    },
    // 修改token
    SET_TOKEN(state, obj) {
      setting.cacheToken(obj.token, obj.remember)
      state.token = obj.token
      if (!obj.token) {
        state.user = {}
        state.menus = null
        setting.cacheUser()
      }
    },
    // 设置权限
    SET_PERMISSION(state, data) {
      state.permission = data
    }
  },
  actions: {
    /**
     * 设置节点权限
     * @param {*} commit
     * @param {*} data
     */
    setPermission({ commit }, data) {
      commit('SET_PERMISSION', data)
    },
    /**
     * 缓存token
     * @param commit
     * @param token {String, {token: String, remember: String}}
     */
    setToken({ commit }, token) {
      let remember = true
      if (typeof token === 'object') {
        remember = token.remember
        token = token.token
      }
      commit('SET_TOKEN', { token: token, remember: remember })
    },
    /**
     * 移除token
     * @param commit
     */
    removeToken({ commit }) {
      commit('SET_TOKEN', {})
    },
    /**
     * 设置用户信息
     * @param commit
     * @param user {Object} 用户信息
     */
    setUser({ commit }, user) {
      setting.cacheUser(user)
      commit('SET', { key: 'user', value: user })
    },
    /**
     * 设置用户权限
     * @param commit
     * @param authorities {Array<String>} 权限
     */
    setAuthorities({ commit }, authorities) {
      commit('SET', { key: 'authorities', value: authorities })
    },
    /**
     * 设置用户角色
     * @param commit
     * @param roles {Array<String>} 角色
     */
    setRoles({ commit }, roles) {
      commit('SET', { key: 'roles', value: roles })
    },
    /**
     * 设置用户菜单
     * @param commit
     * @param menus {Array} 菜单
     */
    setMenus({ commit }, menus) {
      commit('SET', { key: 'menus', value: menus })
    },
    /**
     * 获取用户菜单路由
     * @param commit
     * @returns {Promise} {Array}
     */
    getMenus({ commit }) {
      return new Promise((resolve, reject) => {
        if (!setting.menuUrl) {
          const { menus, homePath } = formatMenus(setting.menus)
          commit('SET', { key: 'menus', value: menus })
          return resolve({ menus: menus, home: homePath })
        }
        // 请求接口获取用户菜单
        axios
          .get(setting.menuUrl)
          .then(res => {
            const result = typeof setting.parseMenu === 'function' ? setting.parseMenu(res.data) : res.data
            // 获取用户的信息、角色、权限
            if (result.user) {
              setting.cacheUser(result.user)
              commit('SET', { key: 'user', value: result.user })
              commit('SET', { key: 'roles', value: result.user.roles })
              commit('SET', {
                key: 'authorities',
                value: result.user.authorities
              })
            }
            // 获取用户的菜单
            if (!result.data) {
              console.error('get menus error: ', result)
              return reject(new Error(result.msg))
            }
            // 处理菜单数据格式
            console.log(result.data)
            result.data.push(
              {
                id: 100,
                pid: 0,
                title: '商品',
                path: '/goods',
                children: [
                  {
                    id: 101,
                    pid: 1,
                    title: '商品分类',
                    path: '/goods/cate',
                    component: '/goods/cate'
                  },
                  {
                    id: 102,
                    pid: 2,
                    title: '商品规格',
                    path: '/goods/attr',
                    component: '/goods/attr'
                  },
                  {
                    id: 103,
                    pid: 3,
                    title: '商品品牌',
                    path: '/goods/brand',
                    component: '/goods/brand'
                  },
                  {
                    id: 104,
                    pid: 4,
                    title: '商品标签',
                    path: '/goods/label',
                    component: '/goods/label'
                  },
                  {
                    id: 105,
                    pid: 5,
                    title: '商品类型',
                    path: '/goods/type',
                    component: '/goods/type'
                  },
                  {
                    id: 106,
                    pid: 6,
                    title: '商品管理',
                    path: '/goods/list',
                    component: '/goods/list'
                  }
                ]
              },
              {
                id: 101,
                pid: 1,
                title: '仓库',
                path: '/depot',
                children: [
                  {
                    id: 101,
                    pid: 1,
                    title: '仓库栏目',
                    path: '/depot/column',
                    component: '/depot/column'
                  },
                  {
                    id: 102,
                    pid: 2,
                    title: '仓库供应商',
                    path: '/depot/supplier',
                    component: '/depot/supplier'
                  },
                  {
                    id: 103,
                    pid: 3,
                    title: '仓库商品',
                    path: '/depot/list',
                    component: '/depot/list'
                  }
                ]
              },
              {
                title: '仓库货架',
                path: '/storage',
                children: [
                  {
                    title: '货架商品',
                    path: '/storage/goods',
                    component: '/storage/goods'
                  },
                  {
                    title: '货架配置',
                    path: '/storage/config',
                    component: '/storage/config'
                  },
                  {
                    title: '箱子配置',
                    path: '/storage/box',
                    component: '/storage/box'
                  },
                  {
                    title: '箱子规格',
                    path: '/storage/spec',
                    component: '/storage/spec'
                  },
                  {
                    title: '库存整合',
                    path: '/storage/integration',
                    component: '/storage/integration'
                  }
                ]
              }
            )
            const { menus, homePath } = formatMenus(result.data, setting.parseMenuItem)
            commit('SET', { key: 'menus', value: menus })

            resolve({ menus: menus, home: homePath })
          })
          .catch(e => {
            reject(e)
          })
      })
    }
  }
}
